package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    Result result=null;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ShowOrderDao showOrderDao;

    /**
     * 预约
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public Result order(Map map) throws Exception {

        //拿到string类型的当前日期
        String orderDate = (String) map.get("orderDate");
        //转换为date类型的当前日期
        Date date = DateUtils.parseString2Date(orderDate);
        //查看当前日期是否有预设
        OrderSetting orderSetting=orderSettingDao.findByOrderDate(date);
        if(orderSetting==null){
            result=new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //查看此预设的可预订人数是否已满
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if(number<=reservations){
            //预约已满，不能预约
            result=new Result(false,MessageConstant.ORDER_FULL);
        }

        //检查用户是否为会员，若不是先注册会员再预定
        String telephone = (String) map.get("telephone");
        Member member=memberDao.findByTelephone(telephone);

        if(member!=null){
            //是会员
            //根据memberId，setmealId,date 查看用户是否重复预约
            Integer memberId = member.getId();
            Integer setmealId = (Integer) map.get("setmealId");
            Order order = new Order(memberId, date, null, null, setmealId);
            List<Order> list=orderDao.findByCondition(order);
            if(list.size()>0 ||list!=null){
                //已经完成了预约，不能重复预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }

        //可以预约， 已预约人数加‘1’
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        if(member==null){
            //不是会员
            //先注册
            member =new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);


        }

        //保存预约信息到ordersetting表
        Order order = new Order(member.getId(),
                date,
                (String) map.get("orderType"),
                Order.ORDERSTATUS_NO,
                Integer.parseInt((String) map.get("setmealId"))

        );
        orderDao.add(order);
        return  new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());


        //预定成功，更新当日的已预定人数

    }

    /**
     * 查询订单
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Map findById(int id) throws Exception {

         Map map=orderDao.findById(id);
         if(map!=null){
            //处理日期格式
             Date orderDate = (Date) map.get("orderDate");
             map.put("orderDate",DateUtils.parseDate2String(orderDate));

         }
         return  map;
    }


    /**
     * 电脑端预约
     * @param newOrder
     * @param phoneNumber
     * @param name
     * @return
     */
//
//    添加
    @Override
    public Result orderByComputer(Order newOrder, String phoneNumber, String name) {
//        添加前先判断
        OrderSetting orderSetting = null;
        try {
            orderSetting = orderSettingDao.findByOrderDate(newOrder.getOrderDate());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(orderSetting == null){
//            指定日期没有进行预约设置,无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
//        2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法完成预约
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations>=number){
//            已经约满,无法预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }
//        3、检验用户是否重复预约(同一个用户同一天预约了同一个套餐),如果是重复套餐则无法预约
        Member member = memberDao.findByTelephone(phoneNumber);//根据手机号判断用户身份是否是会员
        if(member!=null){
            Integer memberId = member.getId();//会员ID
            Order order = new Order(memberId,
                   newOrder.getOrderDate(),null,null,
                    newOrder.getSetmealId());
//            根据条件进行查询
            List<Order> list= orderDao.findByCondition(order);
            if(list!=null&&list.size()>0){
//              用户已经重复预约,无法再次预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }

        }else { //不是会员,进行会员自动注册
//        4、检查当前用户是否为会员，如果是会员则直接完成预约，否则自动完成注册并预约
            member = new Member();
            member.setPhoneNumber(phoneNumber);
            member.setIdCard("123456789012345");
            member.setName(name);
            member.setSex("1");
            member.setRegTime(new Date());//util的Date
            memberDao.add(member);
        }

//        5、预约成功,更新当日的已预约人数
        newOrder.setMemberId(member.getId());   //设置会员ID
        orderDao.add(newOrder);                //添加请求

        orderSetting.setReservations(orderSetting.getReservations()+1);//预约人数+1
        orderSettingDao.editReservationsByOrderDate(orderSetting);//更新展示预约人数
        return new Result(true,MessageConstant.ORDER_SUCCESS,newOrder.getId());//预约成功
    }

    /**
     * 取消预约
     * @param orderId
     */
//
    @Override
    public void cancel(int orderId) {
        Map map = orderDao.findById(orderId);
        showOrderDao.cancel(orderId);
        //拿到string类型的当前日期
        java.sql.Date date = (java.sql.Date) map.get("orderDate");
        //转换为date类型的当前日期
//        Date date = null;
//        try {
//            date = DateUtils.parseString2Date(orderDate);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //查找当前预设设置
        OrderSetting orderSetting=orderSettingDao.findByOrderDate(date);
        orderSetting.setReservations(orderSetting.getReservations()-1);//预约人数-1
        orderSettingDao.editReservationsByOrderDate(orderSetting);//更新展示预约人数
    }

    /**
     * 预约信息分页查询
     * @param queryPageBean
     * @return
     */
//  分页
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //        获取三个参数
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //开启分页
        PageHelper.startPage(currentPage,pageSize);
        //查询并赋值给Page托管类
        Page<ShowOrder> page=showOrderDao.findPage(queryString);    //封装ShowOrder
        long total = page.getTotal();
        List<ShowOrder> result = page.getResult();
        return new PageResult(total,result);
    }

    /**
     * 通知短信发送
     * @param orderId
     * @param type
     */
//
    @Override
    public void sendMessage(int orderId, String type) {
//                发送短信提示用户
        Member member = orderDao.findMemberByOrderId(orderId);
//        System.out.println(member);
        String telephone = member.getPhoneNumber();
        if("success".equalsIgnoreCase(type)){
            try {
                System.out.println("发送预约成功短信");
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone, "你已成功预约");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            try {
                System.out.println("发送取消预约短信");
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone, "您的预约已取消");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
